package org.collector.data.controllerdata;

import java.util.LinkedList;
import java.util.Queue;

import org.apache.http.client.HttpClient;
import org.collector.data.iodata.FailPage;
import org.collector.data.iodata.IUrl;
import org.collector.data.iodata.SuccPage;
import org.collector.util.HttpClientTools;
import org.workstream.ZDriver;

public class SiteOfProxyStatu extends SiteOfProxyParam{
	private Queue<IUrl> taskQueue;
	public SiteOfProxyStatu(){
		super();
		taskQueue = new LinkedList<IUrl>();
	}
	public boolean addTask(IUrl url){
		synchronized(taskQueue){
			return taskQueue.offer(url);
		}
	}
	public int getQueuelength(){
		synchronized(taskQueue){
			return taskQueue.size();
		}
	}
	private boolean taskFail(IUrl url){
		url.incrementUseCount();
		synchronized(this){
			super.increaseTotalFailTimes();
			super.updateLastErrorTime();
		}
		ZDriver.commitData(new FailPage(url));
		return false;
	}
	private boolean taskSucess(IUrl url,String html){
		synchronized(this){
			super.increaseTotalSucessTimes();
			super.updateLastSucessTime();
		}
		ZDriver.commitData(new SuccPage(url,html));
		return true;
	}
	public boolean execute(HttpClient client){
		IUrl url = null;
		synchronized(taskQueue){
			if(taskQueue.size() == 0)
				return false;
			url = taskQueue.poll();
		}
		if(url != null){
			String res = HttpClientTools.ExecuteHttpget(url.getUrl(), client);
			if(res.trim().length() == 0)
				return taskFail(url);
			else
				return taskSucess(url,res);
		}
		return false;
	}
}
